//go:build darwin
// +build darwin

package proxy

import (
	"fmt"
	"gopin/config"
	"os/exec"
	"strings"
)

func (p *Proxy) SetSystemProxy() error {
	// 获取所有网络服务
	out, err := exec.Command("networksetup", "-listallnetworkservices").Output()
	if err != nil {
		return err
	}
	// 解析网络服务列表
	services := strings.Split(string(out), "\n")
	// 第一行通常是提示信息，跳过
	services = services[1:]
	host, port := config.GetInstance().GetProxyHostPort()
	for _, service := range services {
		service = strings.TrimSpace(service)
		if service == "" {
			continue
		}
		// 检查服务是否启用
		if strings.HasPrefix(service, "*") {
			continue // 跳过禁用的服务
		}
		// 设置 HTTP 代理
		err = exec.Command("networksetup", "-setwebproxy", service, host, port).Run()
		if err != nil {
			return fmt.Errorf("failed to set HTTP proxy for %s: %v", service, err)
		}
		// 设置 HTTPS 代理
		err = exec.Command("networksetup", "-setsecurewebproxy", service, host, port).Run()
		if err != nil {
			return fmt.Errorf("failed to set HTTPS proxy for %s: %v", service, err)
		}
	}
	return nil
}

func (p *Proxy) UnsetSystemProxy() error {
	// 获取所有网络服务
	out, err := exec.Command("networksetup", "-listallnetworkservices").Output()
	if err != nil {
		return err
	}
	// 解析网络服务列表
	services := strings.Split(string(out), "\n")
	// 第一行通常是提示信息，跳过
	services = services[1:]
	for _, service := range services {
		service = strings.TrimSpace(service)
		if service == "" {
			continue
		}
		// 检查服务是否启用
		if strings.HasPrefix(service, "*") {
			continue // 跳过禁用的服务
		}
		// 关闭 HTTP 代理
		err = exec.Command("networksetup", "-setwebproxystate", service, "off").Run()
		if err != nil {
			return fmt.Errorf("failed to unset HTTP proxy for %s: %v", service, err)
		}
		// 关闭 HTTPS 代理
		err = exec.Command("networksetup", "-setsecurewebproxystate", service, "off").Run()
		if err != nil {
			return fmt.Errorf("failed to unset HTTPS proxy for %s: %v", service, err)
		}
	}
	return nil
}
